package com.czk.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czk.common.utils.HttpClientUtils;
import com.czk.common.utils.PageUtils;
import com.czk.common.utils.Query;
import com.czk.gulimall.member.dao.MemberDao;
import com.czk.gulimall.member.dao.MemberLevelDao;
import com.czk.gulimall.member.entity.MemberEntity;
import com.czk.gulimall.member.entity.MemberLevelEntity;
import com.czk.gulimall.member.exception.PhoneExsitException;
import com.czk.gulimall.member.exception.UsernameExsitException;
import com.czk.gulimall.member.service.MemberService;
import com.czk.gulimall.member.vo.MemberLoginVo;
import com.czk.gulimall.member.vo.MemberRegistVo;
import com.czk.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity entity = new MemberEntity();
        MemberDao memberDao = this.baseMapper;
        // 设置默认等级
        MemberLevelEntity memberLevelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(memberLevelEntity.getId());
        // 检查用户名和手机号是否唯一，为了然后controller能感知异常，异常机制
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());

        // 手机号
        entity.setMobile(vo.getPhone());
        // 用户名
        entity.setUsername(vo.getUserName());
        // 密码 密码进行加密处理
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encode);
        // 其他默认信息
        entity.setNickname(vo.getUserName());
        memberDao.insert(entity);

    }

    @Override
    public void checkEmailUnique(String email) {

    }

    @Override
    public void checkUserNameUnique(String userName) throws UsernameExsitException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count > 0) {
            throw new UsernameExsitException();
        }

    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExsitException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExsitException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {
        //
        String loginAcct = memberLoginVo.getLoginAcct();
        String password = memberLoginVo.getPassword();
        // 去数据库查询
        MemberDao baseMapper = this.baseMapper;
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginAcct).or().eq("mobile", loginAcct));
        if (memberEntity == null) {
            // 登陆失败
            return null;
        } else {
            // 数据库密码
            String passwordDb = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            // 匹配
            boolean matches = passwordEncoder.matches(password, passwordDb);
            if (matches) {
                return memberEntity;
            } else {
                return null;
            }

        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) {
        // 拿到uid
        String uid = socialUser.getUid();
        // 判断当前社交用户胡是否登陆过系统
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            // 已经注册
            // 更新token和过期时间
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.updateById(update);
            // 返回数据
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        } else {
            // 没有记录，进行注册
            MemberEntity regist = new MemberEntity();
            // 查出当前社交用户的账号信息
            StringBuilder builder = new StringBuilder();
            builder.append("?access_token=" + socialUser.getAccess_token());
            builder.append("&uid=" + socialUser.getUid());
            try {
                HttpResponse response=HttpClientUtils.get_1("https://api.weibo.com/2/users/show.json?access_token="+socialUser.getAccess_token()+"&uid="+socialUser.getUid(),
                        HttpClientUtils.charset,HttpClientUtils.connTimeout,HttpClientUtils.readTimeout);
             //   HttpResponse response = HttpClientUtils.get_1("https://api.weibo.com/2/users/show.json" + builder.toString(), HttpClientUtils.charset, HttpClientUtils.connTimeout, HttpClientUtils.readTimeout);
                if (response.getStatusLine().getStatusCode() == 200) {
                    String string = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(string);
                    // 昵称
                    String name = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    regist.setNickname(name);
                    regist.setGender(Objects.equals(gender, "m") ? 1 : 0);
                }
            } catch (Exception e) {
                // 远程查询名称有问题也不要影响登录
                e.printStackTrace();
            }
            regist.setSocialUid(socialUser.getUid());
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.insert(regist);
            return regist;
        }
    }
}